package com.boot.learning.async;

import java.util.Random;
import java.util.concurrent.Future;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;

/**
 * 异步 
 * @version 1.0
 * @author fuhw
 */
@Component
public class AsyncMethodDemo {
	
public static Random random = new Random();
	
	@Async
	public void executeTask() throws Exception {
		if(doTaskOne().isDone() && doTaskTow().isDone() && doTaskThree().isDone()) {
			System.err.println( "任务完成！" );
		}
	}

	@Async
	public Future<String> doTaskThree() throws InterruptedException{
		System.out.println( "开始做任务三：" );
		long startOne = System.currentTimeMillis();
		Thread.sleep( random.nextInt( 5000 ) );
		long endOne = System.currentTimeMillis();
		System.out.println( "任务三执行完成，耗时：" + (endOne - startOne) + "毫秒" );
		
		return new AsyncResult<>("任务三完成");
	}

	@Async
	public Future<String> doTaskOne() throws InterruptedException{
		System.out.println( "开始做任务一：" );
		long startOne = System.currentTimeMillis();
		Thread.sleep( random.nextInt( 5000 ) );
		long endOne = System.currentTimeMillis();
		System.out.println( "任务一执行完成，耗时：" + (endOne - startOne) + "毫秒" );
		
		return new AsyncResult<>("任务一完成");
	}

	@Async
	public Future<String> doTaskTow() throws InterruptedException{
		System.out.println( "开始做任务二：" );
		long startTow = System.currentTimeMillis();
		Thread.sleep( random.nextInt( 10000 ) );
		long endTow = System.currentTimeMillis();
		System.out.println( "任务二执行完成，耗时：" + (endTow - startTow) + "毫秒" );
		
		return new AsyncResult<>("任务二完成");
	}
}
